/**
 * axios二次封装
 */
import axios from 'axios';
import config from '../config'
import router from './../router'
// 导入信息提示插件
import { ElMessage } from 'element-plus';

// 自定义错误提示
const TOKEN_INVALID = 'TOKEN认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

// 创建axios实例对象，添加全局配置
const service = axios.create({
  baseURL: config.baseApi,
  timeout: 8000,
})

// 请求拦截
service.interceptors.request.use((req) => {
  // TO-DO
  const headers = req.headers
  if (!headers.Authorization) headers.Authorization = 'Bear Jack'
  return req
})

// 响应拦截
service.interceptors.response.use((res) => {
  const { code, data, msg } = res.data;//解构
  if (code === 200) {//状态码成功
    return data;
  } else if (code === 40001) {//状态码失败
    ElMessage.error(TOKEN_INVALID);
    setTimeout(() => {
      router.push('/login')
    }, 1500);
    // 抛出异常
    return Promise.reject(TOKEN_INVALID)
  } else {//请求失败
    ElMessage.error(msg || NETWORK_ERROR);
    return Promise.reject(msg || NETWORK_ERROR)
  }
})

/**
 * 请求核心函数
 * @param{*}options请求配置
 */
function request(options) {
  options.method = options.method || 'get'
  if (options.method.toLowerCase() === 'get') {
    options.params = options.data;
  }
  // 判断mock是否局部开启 以局部为准
  if (typeof options.mock != 'undefined') {
    config.mock = options.mock;
  }
  if (config.env === 'production') {
    // 生成环境调线上接口地址
    service.defaults.baseURL = config.baseApi
  } else {
    service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
  }
  return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
  request[item] = (url, data, options) => {
    return request({
      url, data, method: item, ...options
    })
  }
})

export default request;